<template>
  <div class="channel-evaluation">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>渠道评估</span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
              style="width: 240px"
            />
            <el-button type="primary" @click="handleExport" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出评估报告
            </el-button>
          </div>
        </div>
      </template>

      <!-- 评估指标说明 -->
      <el-alert
        title="渠道评估说明"
        type="info"
        :closable="false"
        class="evaluation-info"
      >
        <div class="evaluation-criteria">
          <p><strong>评分标准：</strong></p>
          <ul>
            <li>成功率 (40%)：渠道推送成功率</li>
            <li>稳定性 (25%)：渠道连接稳定性</li>
            <li>响应速度 (20%)：平均响应时间</li>
            <li>可用性 (15%)：渠道在线时长</li>
          </ul>
          <p><strong>评级标准：</strong></p>
          <ul>
            <li>A级 (90-100分)：优秀渠道，优先推荐</li>
            <li>B级 (80-89分)：良好渠道，正常使用</li>
            <li>C级 (70-79分)：一般渠道，需要关注</li>
            <li>D级 (60-69分)：较差渠道，建议优化</li>
            <li>E级 (0-59分)：差渠道，考虑替换</li>
          </ul>
        </div>
      </el-alert>

      <!-- 评估概览 -->
      <el-row :gutter="20" class="evaluation-overview">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="overview-card excellent">
            <div class="overview-icon">
              <el-icon size="32" color="#67C23A">
                <Trophy />
              </el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-count">{{ overviewData.excellentCount }}</div>
              <div class="overview-label">A级渠道</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="overview-card good">
            <div class="overview-icon">
              <el-icon size="32" color="#409EFF">
                <Medal />
              </el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-count">{{ overviewData.goodCount }}</div>
              <div class="overview-label">B级渠道</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="overview-card average">
            <div class="overview-icon">
              <el-icon size="32" color="#E6A23C">
                <StarFilled />
              </el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-count">{{ overviewData.averageCount }}</div>
              <div class="overview-label">C级渠道</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="overview-card poor">
            <div class="overview-icon">
              <el-icon size="32" color="#F56C6C">
                <Warning />
              </el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-count">{{ overviewData.poorCount + overviewData.badCount }}</div>
              <div class="overview-label">D/E级渠道</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-section">
        <el-col :xs="24" :lg="12">
          <el-card>
            <template #header>
              <span>渠道评分分布</span>
            </template>
            <div ref="scoreDistributionChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card>
            <template #header>
              <span>渠道综合评分雷达图</span>
            </template>
            <div ref="radarChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细评估表格 -->
      <el-card class="evaluation-table">
        <template #header>
          <span>渠道详细评估</span>
          <div class="table-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索渠道名称"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
            <el-select
              v-model="filterRank"
              placeholder="筛选评级"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="A级" value="A" />
              <el-option label="B级" value="B" />
              <el-option label="C级" value="C" />
              <el-option label="D级" value="D" />
              <el-option label="E级" value="E" />
            </el-select>
          </div>
        </template>
        
        <el-table
          :data="filteredTableData"
          border
          stripe
          style="width: 100%"
          :default-sort="{ prop: 'score', order: 'descending' }"
        >
          <el-table-column type="expand">
            <template #default="{ row }">
              <div class="evaluation-detail">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="成功率得分">
                    {{ row.effectiveness }}分 (权重40%)
                  </el-descriptions-item>
                  <el-descriptions-item label="稳定性得分">
                    {{ row.stability }}分 (权重25%)
                  </el-descriptions-item>
                  <el-descriptions-item label="响应速度得分">
                    {{ row.responseQuality }}分 (权重20%)
                  </el-descriptions-item>
                  <el-descriptions-item label="可用性得分">
                    {{ Math.round((row.score - row.effectiveness * 0.4 - row.stability * 0.25 - row.responseQuality * 0.2) / 0.15) }}分 (权重15%)
                  </el-descriptions-item>
                  <el-descriptions-item label="成功率" :span="2">
                    {{ row.successRate }}%
                  </el-descriptions-item>
                  <el-descriptions-item label="平均响应时间" :span="2">
                    {{ row.avgResponseTime }}ms
                  </el-descriptions-item>
                  <el-descriptions-item label="建议" :span="2">
                    <el-alert
                      :title="row.recommendation"
                      :type="getRecommendationType(row.score)"
                      :closable="false"
                      size="small"
                    />
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="channelName" label="渠道名称" min-width="150" />
          <el-table-column prop="channelType" label="渠道类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getChannelTypeTag(row.channelType)" size="small">
                {{ getChannelTypeLabel(row.channelType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="score" label="综合评分" width="100" sortable>
            <template #default="{ row }">
              <div class="score-display">
                <span class="score-value">{{ row.score }}</span>
                <el-progress
                  :percentage="row.score"
                  :color="getScoreColor(row.score)"
                  :stroke-width="6"
                  :show-text="false"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="rank" label="评级" width="80">
            <template #default="{ row }">
              <el-tag :type="getRankTagType(row.rank)" size="small">
                {{ row.rank }}级
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="effectiveness" label="成功率" width="100" sortable>
            <template #default="{ row }">
              {{ row.effectiveness }}分
            </template>
          </el-table-column>
          <el-table-column prop="stability" label="稳定性" width="100" sortable>
            <template #default="{ row }">
              {{ row.stability }}分
            </template>
          </el-table-column>
          <el-table-column prop="responseQuality" label="响应速度" width="100" sortable>
            <template #default="{ row }">
              {{ row.responseQuality }}分
            </template>
          </el-table-column>
          <el-table-column label="建议" min-width="200">
            <template #default="{ row }">
              <el-text type="primary" size="small">
                {{ row.recommendation }}
              </el-text>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getChannelEvaluation } from '@/api/channel'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const dateRange = ref<string[]>([])
const searchText = ref('')
const filterRank = ref('')
const tableData = ref<any[]>([])
const overviewData = reactive({
  excellentCount: 0,
  goodCount: 0,
  averageCount: 0,
  poorCount: 0,
  badCount: 0
})

// 图表实例
let scoreDistributionChart: echarts.ECharts | null = null
let radarChart: echarts.ECharts | null = null

// DOM引用
const scoreDistributionChartRef = ref<HTMLElement>()
const radarChartRef = ref<HTMLElement>()

// 计算属性 - 过滤后的表格数据
const filteredTableData = computed(() => {
  let filtered = tableData.value
  
  if (searchText.value) {
    filtered = filtered.filter(item => 
      item.channelName.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  if (filterRank.value) {
    filtered = filtered.filter(item => item.rank === filterRank.value)
  }
  
  return filtered
})

// 初始化日期范围（最近30天）
const initDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  dateRange.value = [
    start.toISOString().split('T')[0],
    end.toISOString().split('T')[0]
  ]
}

// 获取评估数据
const fetchEvaluationData = async () => {
  loading.value = true
  try {
    const params = {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1]
    }
    const { data } = await getChannelEvaluation(params)
    tableData.value = data.channels
    
    // 更新概览数据
    overviewData.excellentCount = data.channels.filter((c: any) => c.rank === 'A').length
    overviewData.goodCount = data.channels.filter((c: any) => c.rank === 'B').length
    overviewData.averageCount = data.channels.filter((c: any) => c.rank === 'C').length
    overviewData.poorCount = data.channels.filter((c: any) => c.rank === 'D').length
    overviewData.badCount = data.channels.filter((c: any) => c.rank === 'E').length
    
    // 初始化图表
    setTimeout(() => {
      initCharts(data)
    }, 100)
  } catch (error) {
    ElMessage.error('获取评估数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = (data: any) => {
  // 评分分布图
  if (scoreDistributionChartRef.value) {
    scoreDistributionChart = echarts.init(scoreDistributionChartRef.value)
    const distributionData = [
      { name: 'A级(90-100)', value: overviewData.excellentCount },
      { name: 'B级(80-89)', value: overviewData.goodCount },
      { name: 'C级(70-79)', value: overviewData.averageCount },
      { name: 'D级(60-69)', value: overviewData.poorCount },
      { name: 'E级(0-59)', value: overviewData.badCount }
    ]
    
    const scoreDistributionOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [{
        name: '评分分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: distributionData,
        color: ['#67C23A', '#409EFF', '#E6A23C', '#F56C6C', '#909399']
      }]
    }
    scoreDistributionChart.setOption(scoreDistributionOption)
  }

  // 雷达图
  if (radarChartRef.value) {
    radarChart = echarts.init(radarChartRef.value)
    const avgScores = calculateAverageScores(data.channels)
    
    const radarOption = {
      tooltip: {},
      legend: {
        data: ['平均得分']
      },
      radar: {
        indicator: [
          { name: '成功率', max: 100 },
          { name: '稳定性', max: 100 },
          { name: '响应速度', max: 100 },
          { name: '可用性', max: 100 }
        ],
        shape: 'circle',
        splitNumber: 5,
        axisName: {
          color: 'rgb(238, 197, 102)'
        },
        splitLine: {
          lineStyle: {
            color: [
              'rgba(238, 197, 102, 0.1)',
              'rgba(238, 197, 102, 0.2)',
              'rgba(238, 197, 102, 0.4)',
              'rgba(238, 197, 102, 0.6)',
              'rgba(238, 197, 102, 0.8)',
              'rgba(238, 197, 102, 1)'
            ].reverse()
          }
        },
        splitArea: {
          show: false
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(238, 197, 102, 0.5)'
          }
        }
      },
      series: [{
        name: '渠道评估',
        type: 'radar',
        data: [{
          value: [avgScores.effectiveness, avgScores.stability, avgScores.responseQuality, avgScores.availability],
          name: '平均得分',
          areaStyle: {
            color: 'rgba(255, 255, 255, 0.5)'
          }
        }]
      }]
    }
    radarChart.setOption(radarOption)
  }
}

// 计算平均分
const calculateAverageScores = (channels: any[]) => {
  const total = channels.length
  if (total === 0) return { effectiveness: 0, stability: 0, responseQuality: 0, availability: 0 }
  
  const sum = channels.reduce((acc, channel) => ({
    effectiveness: acc.effectiveness + channel.effectiveness,
    stability: acc.stability + channel.stability,
    responseQuality: acc.responseQuality + channel.responseQuality,
    availability: acc.availability + Math.round((channel.score - channel.effectiveness * 0.4 - channel.stability * 0.25 - channel.responseQuality * 0.2) / 0.15)
  }), { effectiveness: 0, stability: 0, responseQuality: 0, availability: 0 })
  
  return {
    effectiveness: Math.round(sum.effectiveness / total),
    stability: Math.round(sum.stability / total),
    responseQuality: Math.round(sum.responseQuality / total),
    availability: Math.round(sum.availability / total)
  }
}

// 日期范围改变
const handleDateChange = () => {
  fetchEvaluationData()
}

// 搜索
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

// 导出评估报告
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 这里需要实现导出功能
    ElMessage.success('评估报告导出成功')
  } catch (error) {
    ElMessage.error('评估报告导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 工具函数
const getChannelTypeTag = (type: string) => {
  const tagTypes: Record<string, string> = {
    upstream: 'info',
    downstream: 'success',
    bank: 'primary',
    consumer_finance: 'warning',
    small_loan: 'danger'
  }
  return tagTypes[type] || 'info'
}

const getChannelTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    upstream: '上游渠道',
    downstream: '下游渠道',
    bank: '银行',
    consumer_finance: '消费金融',
    small_loan: '小贷公司'
  }
  return labels[type] || type
}

const getRankTagType = (rank: string) => {
  const tagTypes: Record<string, string> = {
    A: 'success',
    B: 'primary',
    C: 'warning',
    D: 'danger',
    E: 'info'
  }
  return tagTypes[rank] || 'info'
}

const getScoreColor = (score: number) => {
  if (score >= 90) return '#67C23A'
  if (score >= 80) return '#409EFF'
  if (score >= 70) return '#E6A23C'
  if (score >= 60) return '#F56C6C'
  return '#909399'
}

const getRecommendationType = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'info'
  if (score >= 70) return 'warning'
  return 'error'
}

// 窗口大小改变时重新渲染图表
const handleResize = () => {
  scoreDistributionChart?.resize()
  radarChart?.resize()
}

// 生命周期
onMounted(() => {
  initDateRange()
  fetchEvaluationData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  scoreDistributionChart?.dispose()
  radarChart?.dispose()
})
</script>

<style scoped>
.channel-evaluation {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 评估说明 */
.evaluation-info {
  margin-bottom: 20px;
}

.evaluation-criteria {
  line-height: 1.6;
}

.evaluation-criteria ul {
  margin: 10px 0;
  padding-left: 20px;
}

.evaluation-criteria li {
  margin: 5px 0;
}

/* 评估概览 */
.evaluation-overview {
  margin-bottom: 30px;
}

.overview-card {
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.overview-card.excellent {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border: 1px solid #b3d8ff;
}

.overview-card.good {
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f1ff 100%);
  border: 1px solid #91caff;
}

.overview-card.average {
  background: linear-gradient(135deg, #fffbe6 0%, #fff8e6 100%);
  border: 1px solid #ffe58f;
}

.overview-card.poor {
  background: linear-gradient(135deg, #fff1f0 0%, #ffebe6 100%);
  border: 1px solid #ffccc7;
}

.overview-icon {
  padding: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.overview-info {
  flex: 1;
}

.overview-count {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.overview-label {
  font-size: 14px;
  color: #606266;
}

/* 图表区域 */
.chart-section {
  margin-bottom: 20px;
}

.chart-container {
  height: 350px;
  width: 100%;
}

/* 详细评估表格 */
.evaluation-table {
  margin-top: 20px;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.evaluation-detail {
  padding: 20px;
  background-color: #f5f7fa;
}

.score-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.score-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .channel-evaluation {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .overview-card {
    flex-direction: column;
    text-align: center;
  }
  
  .chart-container {
    height: 250px;
  }
  
  .table-actions {
    flex-direction: column;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .overview-count {
    font-size: 20px;
  }
  
  .chart-container {
    height: 200px;
  }
}
</style>